<template>
  <el-form ref="formRef" :model="uploadInfo" label-width="80px" status-icon>
    <el-form-item
      label="封面"
      prop="coverPath"
      :rules="{
        required: true,
        message: '请选择封面',
      }"
    >
      <!-- 用于设置封面上传提示，其他没有什么用 -->
      <el-input v-model="uploadInfo.coverPath" style="display: none" />
      <el-upload
        class="cover-uploader"
        action=""
        accept=".jpg,.jpeg,.png"
        :show-file-list="false"
        :before-upload="uploadCoverBefore"
        style="border: 1px solid rgb(209, 209, 209)"
      >
        <div
          v-if="uploadInfo.coverPath"
          class="cover-uploader-image"
          :style="{
            'background-image':
              'url(&#34;' + commonApi.getCover(uploadInfo.coverPath) + '&#34;)',
          }"
        ></div>
        <el-icon v-else class="cover-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item
      label="标题"
      prop="title"
      :rules="{
        required: true,
        message: '标题不可为空',
        trigger: 'blur',
      }"
    >
      <el-col :span="20">
        <el-input v-model="uploadInfo.title" maxlength="50" show-word-limit />
      </el-col>
    </el-form-item>
    <el-form-item
      label="类型"
      prop="type"
      :rules="{
        required: true,
        message: '类型是必选项',
      }"
    >
      <el-radio-group v-model="uploadInfo.type">
        <el-radio-button label="1">转载</el-radio-button>
        <el-radio-button label="0">自制</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item
      label="分区"
      prop="channel"
      :rules="{
        required: true,
        message: '分区是必选项',
      }"
    >
      <el-select
        v-model="uploadInfo.channel"
        placeholder="点击选择"
        @change="getRecommendTags"
      >
        <el-option
          v-for="key in Object.keys(store().channelList)"
          :label="store().channelList[Number(key)].content"
          :value="Number(key)"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="标签">
      <el-input
        v-model="tagInput"
        size="small"
        maxlength="10"
        style="width: 90px"
        @keyup.enter="addTag({ name: tagInput })"
        @blur="addTag({ name: tagInput })"
        placeholder=" + New Tag "
      />
      <el-tag
        v-for="tag in selectedTags"
        :key="tag"
        class="mx-1 upload-tag__selected"
        closable
        :disable-transitions="false"
        @close="deleteTag(tag)"
        round
        effect="dark"
      >
        {{ tag.name }}
      </el-tag>
    </el-form-item>
    <el-form-item>
      <el-form-item label="推荐标签" class="upload-tag__recommend">
        <div>
          <el-check-tag
            v-for="tag in recommendTags"
            :key="tag.id"
            class="mx-1"
            :disable-transitions="false"
            round
            :checked="tag.checked"
            @change="addRecommendTag(tag)"
          >
            {{ tag.name }}
          </el-check-tag>
        </div>
      </el-form-item>
    </el-form-item>

    <el-form-item label="简介">
      <el-col :span="20">
        <el-input
          v-model="uploadInfo.describe"
          type="textarea"
          maxlength="1440"
          show-word-limit
        />
      </el-col>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        v-loading.fullscreen.lock="fullScreenLoading"
        @click="onSubmit(formRef)"
      >
        发布
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, onUnmounted } from "vue";
import { Plus } from "@element-plus/icons-vue";
import commonApi from "@/api/common";
import videoApi from "@/api/video";
import tagApi from "@/api/tag";
import { errorNotify, successNotify } from "@/utils/common";
import store from "@/store/store";
import { Video } from "@/types/video";
import type { UploadRawFile, FormInstance } from "element-plus";
import { Tag } from "@/types/tag";

const props = defineProps({
  videoInfo: {
    type: Object as () => Video,
    require: false,
  },
  type: {
    type: Number, // 1:添加，2:修改
    require: false,
    default: 1,
  },
});
const emit = defineEmits(["nowTip"]);

const formRef = ref<FormInstance>();
// 上传视频信息
const uploadInfo = ref<Video>(<Video>{});

// 供父组件设置视频文件名
const setVideoName = (name: string) => {
  uploadInfo.value.videoPath = name;
};
const setCoverName = (name: string) => {
  uploadInfo.value.coverPath = name;
};
defineExpose({ setVideoName, setCoverName });
// 上传封面
const uploadCoverBefore = (rawFile: UploadRawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    errorNotify("封面大小不能超过2MB");
    return false;
  }
  let formData = new FormData();
  formData.append("file", rawFile);
  commonApi.uploadCover(formData).then((res) => {
    // 获取文件名
    if (res.data.code === 0) {
      uploadInfo.value.coverPath = res.data.data;
    }
  });
  return false;
};

// 标签
const tagInput = ref<string>("");
const recommendTags = ref<Tag[]>([]);
const selectedTags = ref<Tag[]>([]);
// 删除tag
const deleteTag = (tag: Tag) => {
  tag.checked = false;
  selectedTags.value.splice(selectedTags.value.indexOf(tag), 1);
};
// 通过channel获取推荐的tag
const getRecommendTags = (channelId: number) => {
  tagApi.getByChannel(channelId).then((res) => {
    if (res.data.code === 0) {
      recommendTags.value = res.data.data;
      for (let i = 0; i < recommendTags.value.length; i++) {
        recommendTags.value[i].checked = false;
      }
    }
  });
};
const addTag = (tag: Tag) => {
  if (selectedTags.value.length >= 10) {
    errorNotify("标签数不能超过10个");
    return;
  }
  if (tag.name) {
    for (let sTag of selectedTags.value) {
      if (sTag.name === tag.name) {
        errorNotify("标签已存在");
        return;
      }
    }
    selectedTags.value.push(tag);
  }
  tagInput.value = "";
};
// 添加推荐tag
const addRecommendTag = (tag: Tag) => {
  tag.checked = !tag.checked;
  if (tag.checked) {
    addTag(tag);
  } else {
    deleteTag(tag);
  }
};

const fullScreenLoading = ref(false);
// 验证并提交
const onSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      fullScreenLoading.value = true;
      // tag信息附加上传
      // @ts-ignore
      uploadInfo.value.tags = selectedTags.value;
      if (props.type === 1) {
        saveVideoInfo();
      } else {
        updateVideoInfo();
      }
    } else {
      return false;
    }
  });
};

const saveVideoInfo = () => {
  videoApi.save(uploadInfo.value).then((res) => {
    fullScreenLoading.value = false;
    if (res.data.code === 0) {
      emit("nowTip", res.data.data.id);
      // removeEventListener('beforeunload', beforeCloseWindow);
    }
  });
};

const updateVideoInfo = async () => {
  const { code, data } = await videoApi.update(uploadInfo.value);
  fullScreenLoading.value = false;
  if (code === 0) {
    successNotify(data);
    emit("nowTip", true);
  }
};

const getTags = async (videoId: Video["id"]) => {
  const { code, data } = await tagApi.getByVideoId(videoId);
  if (code === 0) {
    selectedTags.value = data;
  }
};

const watchProps = watch(
  () => props,
  (val) => {
    // 判断当前是否是修改界面
    let videoId = props.videoInfo?.id;
    if (props.type === 2 && videoId !== undefined) {
      //@ts-ignore
      uploadInfo.value = props.videoInfo;
      // 获取tag
      getTags(videoId);
    }
  },
  { immediate: true, deep: true }
);

// 监听刷新和关闭，提示修改未保存
onMounted(() => {
  if (props.type === 1) {
    window.addEventListener("beforeunload", beforeCloseWindow);
  }
});

const beforeCloseWindow = (e: Event) => {
  e = e || window.event;
  if (e) {
    // 在这里阻止默认的刷新，弹出弹框
    e.preventDefault();
  }
  return "关闭";
};

onUnmounted(() => {
  if (props.type === 1) {
    window.removeEventListener("beforeunload", beforeCloseWindow);
  }
  watchProps();
});
</script>

<style lang="scss" scoped>
form {
  margin-top: 40px;

  & > div {
    margin-top: 30px;
  }

  .mx-1 {
    margin: 5px;
  }

  .upload-tag__recommend {
    position: relative;
    top: -20px;
    left: -10px;
    text-align: left;
  }

  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 180px;
    height: 120px;
    text-align: center;
  }
}
</style>

<style lang="scss">
.cover-uploader {
  width: 200px;
  height: 120px;

  & > * {
    position: relative;
    height: 100%;
    width: 100%;
  }

  .cover-uploader-image {
    width: 100%;
    height: 100%;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
  }
}
</style>
